﻿using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace OcelotWebApi01.Common
{
    public static class ConsulHelper
    {
        public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IConfiguration configuration)
        {
            var consulClient = new ConsulClient(x =>
            {
                // consul 服务地址(你要注册到哪个consul服务就填写哪个)
                x.Address = new Uri("http://127.0.0.1:8500");
            });
            var registration = new AgentServiceRegistration()
            {
                ID = Guid.NewGuid().ToString(),
                Name = configuration["Consul:serviceName"],// 服务名
                Address = configuration["Consul:serviceAddress"], // 服务绑定IP(也就是你这个项目运行的ip地址)
                Port = int.Parse(configuration["Consul:servicePort"]), // 服务绑定端口(也就是你这个项目运行的端口)
                Check = new AgentServiceCheck()
                {
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册
                    Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔
                    HTTP = configuration["Consul:helthAddress"],//健康检查地址
                    Timeout = TimeSpan.FromSeconds(5)
                }
            };
            // 服务注册
            consulClient.Agent.ServiceRegister(registration).Wait();
            // 应用程序终止时，服务取消注册
            //lifetime.ApplicationStopping.Register(() =>
            //{
            //    consulClient.Agent.ServiceDeregister(registration.ID).Wait();
            //});
            return app;
        }
    }
}
